<?php
/**
 * @Author: gan
 * @Description: 缓存Traits
 * @File:  CacheablesTrait
 * @Version: 1.0.0
 * @Date: 2022/5/19 5:03 下午
 */
declare(strict_types=1);

namespace RX\Traits;

use RX\Component\Cache\RedisCache;

trait CacheablesTrait
{
    /**
     * 获取缓存
     * @Author: gan
     * @Description:
     * @Version: 1.0.0
     * @Date: 2022/5/19 5:05 下午
     * @param string $key redis key
     * @param int $ttl ttl
     * @param callable|null $callback 回调函数，一般查询数据
     * @return mixed|null
     */
    public function getCache(string $key, int $ttl, callable $callback = null)
    {
        $cacheData = RedisCache::get($key);
        if (!empty($cacheData)) {
            return $cacheData;
        }
        $value = null;
        if (empty($cacheData) && $callback && is_callable($callback)) {
            $value = call_user_func($callback);
        }
        return $value ? $this->setCache($key, $value, $ttl) : null;
    }


    /**
     * 设置缓存
     * @Author: gan
     * @Description:
     * @Version: 1.0.0
     * @Date: 2022/5/19 5:06 下午
     * @param string $key redis key
     * @param mixed $value 值
     * @param int $ttl ttl
     * @return mixed
     */
    public function setCache(string $key, $value, int $ttl)
    {
        RedisCache::set($key, $value, $ttl + mt_rand(1, 10));
        return $value;
    }


    /**
     * 清理缓存
     * @Author: gan
     * @Description:
     * @Version: 1.0.0
     * @Date: 2022/5/19 5:06 下午
     * @param string $key redis  key
     * @param callable|null $callback 回调函数
     * @return mixed
     */
    public function clearCache(string $key, callable $callback = null)
    {
        return RedisCache::callbackDel($key, $callback);
    }
}
